package com.pianzhu.blockchainemr.service.impl;

import com.pianzhu.blockchainemr.mapper.EnrollMapper;
import com.pianzhu.blockchainemr.mapper.UserMapper;
import com.pianzhu.blockchainemr.pojo.Param.EnrollParam;
import com.pianzhu.blockchainemr.service.EnrollService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EnrollServiceImpl implements EnrollService {
    @Autowired
    private EnrollMapper enrollMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 插入医生： 1。新建用户，传入username，password，name，usertype；
     *            2.查询刚刚插入的用户的id，返回userId。
     *            2。新建医生，传入userId，hospitalId。
     * 插入患者： 1。新建用户，传入username，password，name，usertype；
     *            2.查询刚刚插入的用户的id，返回userId。
     *            2。新建患者，传入userId。
     */
    @Override
    @Transactional// 事务注解，保证插入数据和更新数据在同一个事务中
    public int enroll(EnrollParam data) {
        if (userMapper.selectByUsername(data.getUsername())!= null){
            return 0;
        }
        if (data.getUsertype().equals("医")){
            enrollMapper.enrollUser(data);
            int userId = enrollMapper.getUserId(data);
            enrollMapper.enrollDoctor(data.getHospitalId(), userId);
        }else {
            enrollMapper.enrollUser(data);
            int userId = enrollMapper.getUserId(data);
            enrollMapper.enrollPatient(data, userId);
        }
        return 1;
    }
}
